﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

using libPlugin;

namespace tinterBot
{
    static class jobScheduler
    {
        public static Thread jobThread = new Thread(scheduleLoop);
        public static List<BotJob> jobsToSort = new List<BotJob>();
        static int numberOfJobs = 0;

        static void scheduleLoop()
        {
            while (true)
            {
                for(int i = 0; i < jobsToSort.Count; i++)
                {
                    BotJob job = jobsToSort[i];

                    foreach (IBotPlugin plugin in pluginManager.pluginList)
                    {
                        foreach (BotCommand cmd in plugin.Commands)
                        {
                            if (cmd.commandSyntax.IsMatch(job.commandToProcess))
                            {
                                job.command = cmd;
                                plugin.waitingJobs.Add(job);

                                numberOfJobs++;

                                pluginManager.threadList[pluginManager.pluginList.IndexOf(plugin)].Interrupt();
                            }
                        }
                    }

                    jobsToSort.RemoveAt(i);
                }

                foreach (IBotPlugin plugin in pluginManager.pluginList)
                {
                    if (!(plugin.completedJobs.Count == 0))
                    {
                        List<int> jobsExecuted = new List<int>();

                        for (int i = 0; i < plugin.completedJobs.Count; i++)
                        {
                            networkManager.netWrite(plugin.completedJobs[i].jobResult.NetWrite);
                            Program.ConWrite(plugin.completedJobs[i].jobResult.ConWrite);
                            Program.LogWrite(string.Format("[{0}] {1}\r\n", plugin.Name, plugin.completedJobs[i].jobResult.LogWrite));

                            jobsExecuted.Add(i);

                            numberOfJobs--;
                        }

                        foreach (int job in jobsExecuted)
                        {
                            plugin.completedJobs.RemoveAt(job);
                        }
                    }
                }

                if (jobsToSort.Count == 0 && numberOfJobs == 0)
                {
                    try
                    {
                        Thread.Sleep(Timeout.Infinite);
                    }
                    catch (ThreadInterruptedException)
                    {
                    }
                }
            }
        }
    }
}
